<template>
	<view class="page">
		<!-- 头部导航 -->
		<!-- <view class="header-bag">
			<image src="/static/icon-Get-into@3.png" class="back" @click="goBack"></image>
			<view class="header-center">
				<text>填写生活商家信息</text>
			</view>
		</view> -->

		<!-- 表单内容 -->
		<view class="wrapper">
			<view class="info-box">
				<!-- 店铺名称 -->
				<view class="layouts">
					<view class="label">
						<text class="must-write">*</text>
						<text>店铺名称:</text>
					</view>
					<view class="input-wrapper">
						<input 
							v-model="formData.shopName" 
							type="text" 
							placeholder="请填写真实的店铺名称"
							@input="onInput('shopName')"
						/>
						<image 
							v-if="formData.shopName" 
							src="/static/icon-close.png" 
							class="del-text" 
							@click="clearInput('shopName')"
						></image>
					</view>
				</view>

				<!-- 营业执照名称 -->
				<view class="layouts">
					<view class="label">
						<text class="must-write">*</text>
						<text>营业执照名称:</text>
					</view>
					<view class="input-wrapper">
						<input 
							v-model="formData.licenseName" 
							type="text" 
							placeholder="请填写真实的营业执照名称"
							@input="onInput('licenseName')"
						/>
						<image 
							v-if="formData.licenseName" 
							src="/static/icon-close.png" 
							class="del-text" 
							@click="clearInput('licenseName')"
						></image>
					</view>
				</view>

				<!-- 统一社会信用代码 -->
				<view class="layouts">
					<view class="label">
						<text class="must-write">*</text>
						<text>统一社会信用代码:</text>
					</view>
					<view class="input-wrapper">
						<input 
							v-model="formData.creditId" 
							type="text" 
							placeholder="请填写信用代码"
							@input="onInput('creditId')"
						/>
						<image 
							v-if="formData.creditId" 
							src="/static/icon-close.png" 
							class="del-text" 
							@click="clearInput('creditId')"
						></image>
					</view>
				</view>

				<!-- 负责人姓名 -->
				<view class="layouts">
					<view class="label">
						<text class="must-write">*</text>
						<text>负责人姓名:</text>
					</view>
					<view class="input-wrapper">
						<input 
							v-model="formData.managerName" 
							type="text" 
							placeholder="请填写负责人姓名"
							@input="onInput('managerName')"
						/>
						<image 
							v-if="formData.managerName" 
							src="/static/icon-close.png" 
							class="del-text" 
							@click="clearInput('managerName')"
						></image>
					</view>
				</view>

				<!-- 负责人电话 -->
				<view class="layouts">
					<view class="label">
						<text class="must-write">*</text>
						<text>负责人电话:</text>
					</view>
					<view class="input-wrapper">
						<input 
							v-model="formData.managerTel" 
							type="text" 
							placeholder="请填写负责人电话"
							@input="onInput('managerTel')"
						/>
						<image 
							v-if="formData.managerTel" 
							src="/static/icon-close.png" 
							class="del-text" 
							@click="clearInput('managerTel')"
						></image>
					</view>
				</view>

				<!-- 店铺地址 -->
				<view class="layouts">
					<view class="label">
						<text class="must-write">*</text>
						<text>店铺地址:</text>
					</view>
					<view class="input-wrapper">
						<input 
							v-model="formData.areaName" 
							type="text" 
							placeholder="请选择店铺所属省市"
							readonly
							@click="showAreaPicker"
						/>
					</view>
				</view>

				<!-- 店铺类型 -->
				<view class="layouts">
					<view class="label">
						<text class="must-write">*</text>
						<text>店铺类型:</text>
					</view>
					<view class="input-wrapper">
						<input 
							v-model="formData.shopType" 
							type="text" 
							placeholder="请选择店铺类型"
							readonly
							@click="showTypePicker"
						/>
					</view>
				</view>

				<!-- 店铺详细地址 -->
				<view class="layouts">
					<view class="label">
						<text class="must-write">*</text>
						<text>店铺详细地址:</text>
					</view>
					<view class="input-wrapper">
						<input 
							v-model="formData.shopDetailAddress" 
							type="text" 
							placeholder="请填写店铺详细地址"
							@input="onInput('shopDetailAddress')"
						/>
						<image 
							v-if="formData.shopDetailAddress" 
							src="/static/icon-close.png" 
							class="del-text" 
							@click="clearInput('shopDetailAddress')"
						></image>
					</view>
				</view>
			</view>

			<!-- 提醒文字 -->
			<view class="notice-text">
				提醒 : 以上录入优享优品平台会进行核实
			</view>

			<!-- 下一步按钮 -->
			<view class="next-step" @click="nextStep">
				下一步
			</view>
		</view>

		<!-- 地区选择器 -->
		<view v-if="showAreaSelector" class="picker-container">
			<view class="picker-header">
				<text class="picker-cancel" @click="hidePicker">取消</text>
				<text class="picker-title">选择地区</text>
				<text class="picker-confirm" @click="confirmAreaSelection">确定</text>
			</view>
			<picker-view 
				class="picker-view"
				:value="areaPickerValue"
				@change="onAreaChange"
			>
				<picker-view-column>
					<view v-for="(province, index) in regionData" :key="index">
						{{ province.region_name }}
					</view>
				</picker-view-column>
				<picker-view-column>
					<view v-for="(city, index) in cityData" :key="index">
						{{ city.region_name }}
					</view>
				</picker-view-column>
				<picker-view-column>
					<view v-for="(district, index) in districtData" :key="index">
						{{ district.region_name }}
					</view>
				</picker-view-column>
			</picker-view>
		</view>

		<!-- 店铺类型选择器 -->
		<view v-if="showTypeSelector" class="picker-container">
			<view class="picker-header">
				<text class="picker-cancel" @click="hidePicker">取消</text>
				<text class="picker-title">选择店铺类型</text>
				<text class="picker-confirm" @click="confirmTypeSelection">确定</text>
			</view>
			<picker-view 
				class="picker-view"
				:value="typePickerValue"
				@change="onTypeChange"
			>
				<picker-view-column>
					<view v-for="(type1, index) in categoryData" :key="index">
						{{ type1.name }}
					</view>
				</picker-view-column>
				<picker-view-column>
					<view v-for="(type2, index) in secondCategoryData" :key="index">
						{{ type2.name }}
					</view>
				</picker-view-column>
				<picker-view-column>
					<view v-for="(type3, index) in thirdCategoryData" :key="index">
						{{ type3.name }}
					</view>
				</picker-view-column>
			</picker-view>
		</view>

		<!-- 遮罩层 -->
		<view v-if="showAreaSelector || showTypeSelector" class="mask" @click="hidePicker"></view>
	</view>
</template>

<script>
import { merchantApi } from '@/api/index.js'

export default {
	data() {
		return {
			formData: {
				shopName: '',
				licenseName: '',
				creditId: '',
				managerName: '',
				managerTel: '',
				areaName: '',
				shopType: '',
				shopDetailAddress: ''
			},
			// 地区数据
			regionData: [],
			cityData: [],
			districtData: [],
			selectedRegion: null,
			areaPickerValue: [0, 0, 0],
			showAreaSelector: false,
			
			// 分类数据
			categoryData: [],
			secondCategoryData: [],
			thirdCategoryData: [],
			selectedCategory: null,
			typePickerValue: [0, 0, 0],
			showTypeSelector: false,
			
			// 存储选择的数据
			addrIdArr: [],
			shopClassData: []
		}
	},
	
	onLoad(options) {
		this.loadData()
		if (options.id) {
			this.loadExistingData(options.id)
		}
	},
	
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 加载基础数据
		async loadData() {
			await Promise.all([
				this.loadRegionData(),
				this.loadCategoryData()
			])
		},
		
		// 加载地区数据
		async loadRegionData() {
			try {
				const res = await merchantApi.getAllRegion()
				if (res.r === 0) {
					this.regionData = res.data.gr
					if (this.regionData.length > 0) {
						this.cityData = this.regionData[0].child || []
						if (this.cityData.length > 0) {
							this.districtData = this.cityData[0].child || []
						}
					}
				}
			} catch (error) {
				console.error('加载地区数据失败:', error)
			}
		},
		
		// 加载分类数据
		async loadCategoryData() {
			try {
				const res = await merchantApi.getMerchCategory()
				if (res.r === 0) {
					this.categoryData = res.data.cate
					if (this.categoryData.length > 0) {
						this.secondCategoryData = this.categoryData[0].child || []
						if (this.secondCategoryData.length > 0) {
							this.thirdCategoryData = this.secondCategoryData[0].child || []
						}
					}
				}
			} catch (error) {
				console.error('加载分类数据失败:', error)
			}
		},
		
		// 加载已有数据（编辑模式）
		async loadExistingData(id) {
			try {
				const res = await merchantApi.getApplyList({ id })
				if (res.r === 0 && res.data.aplist.length > 0) {
					const data = res.data.aplist[0]
					this.formData = {
						shopName: data.shop_name,
						licenseName: data.license_name,
						creditId: data.uniform_social_credit_code,
						managerName: data.manager_name,
						managerTel: data.manager_tel,
						areaName: data.area_name,
						shopType: data.merch_type,
						shopDetailAddress: data.shop_detail_address
					}
					
					// 存储地址信息
					this.addrIdArr = [
						{ id: data.shop_province_id, value: data.area_name.split('-')[0] },
						{ id: data.shop_city_id, value: data.area_name.split('-')[1] },
						{ id: data.shop_district_id, value: data.area_name.split('-')[2] }
					]
					
					// 存储分类信息
					if (data.third_cate_id && data.first_cate_id && data.second_cate_id) {
						this.shopClassData = [
							{ id: data.first_cate_id, value: data.merch_type.split('-')[0] },
							{ id: data.second_cate_id, value: data.merch_type.split('-')[1] },
							{ id: data.third_cate_id, value: data.merch_type.split('-')[2] }
						]
					} else if (!data.third_cate_id && data.first_cate_id && data.second_cate_id) {
						this.shopClassData = [
							{ id: data.first_cate_id, value: data.merch_type.split('-')[0] },
							{ id: data.second_cate_id, value: data.merch_type.split('-')[1] }
						]
					}
				}
			} catch (error) {
				console.error('加载已有数据失败:', error)
			}
		},
		
		// 输入事件
		onInput(field) {
			// 可以在这里添加实时验证逻辑
		},
		
		// 清空输入
		clearInput(field) {
			this.formData[field] = ''
		},
		
		// 显示地区选择器
		showAreaPicker() {
			this.showAreaSelector = true
		},
		
		// 显示类型选择器
		showTypePicker() {
			this.showTypeSelector = true
		},
		
		// 隐藏选择器
		hidePicker() {
			this.showAreaSelector = false
			this.showTypeSelector = false
		},
		
		// 确认地区选择
		confirmAreaSelection() {
			const [provinceIndex, cityIndex, districtIndex] = this.areaPickerValue
			const province = this.regionData[provinceIndex]
			const city = this.cityData[cityIndex]
			const district = this.districtData[districtIndex]
			
			if (province && city && district) {
				this.formData.areaName = `${province.region_name}-${city.region_name}-${district.region_name}`
				this.addrIdArr = [
					{ id: province.id, value: province.region_name },
					{ id: city.id, value: city.region_name },
					{ id: district.id, value: district.region_name }
				]
			}
			this.hidePicker()
		},
		
		// 确认类型选择
		confirmTypeSelection() {
			const [firstIndex, secondIndex, thirdIndex] = this.typePickerValue
			const first = this.categoryData[firstIndex]
			const second = this.secondCategoryData[secondIndex]
			const third = this.thirdCategoryData[thirdIndex]
			
			if (first && second) {
				if (third) {
					this.formData.shopType = `${first.name}-${second.name}-${third.name}`
					this.shopClassData = [
						{ id: first.id, value: first.name },
						{ id: second.id, value: second.name },
						{ id: third.id, value: third.name }
					]
				} else {
					this.formData.shopType = `${first.name}-${second.name}`
					this.shopClassData = [
						{ id: first.id, value: first.name },
						{ id: second.id, value: second.name }
					]
				}
			}
			this.hidePicker()
		},
		
		// 地区选择变化
		onAreaChange(e) {
			const [provinceIndex, cityIndex, districtIndex] = e.detail.value
			this.areaPickerValue = e.detail.value
			
			// 更新城市数据
			if (this.regionData[provinceIndex]) {
				this.cityData = this.regionData[provinceIndex].child || []
				// 更新区县数据
				if (this.cityData[cityIndex]) {
					this.districtData = this.cityData[cityIndex].child || []
				}
			}
			
			// 设置选中的地区
			const province = this.regionData[provinceIndex]
			const city = this.cityData[cityIndex]
			const district = this.districtData[districtIndex]
			
			if (province && city && district) {
				this.formData.areaName = `${province.region_name}-${city.region_name}-${district.region_name}`
				this.addrIdArr = [
					{ id: province.id, value: province.region_name },
					{ id: city.id, value: city.region_name },
					{ id: district.id, value: district.region_name }
				]
			}
		},
		
		// 类型选择变化
		onTypeChange(e) {
			const [firstIndex, secondIndex, thirdIndex] = e.detail.value
			this.typePickerValue = e.detail.value
			
			// 更新二级分类数据
			if (this.categoryData[firstIndex]) {
				this.secondCategoryData = this.categoryData[firstIndex].child || []
				// 更新三级分类数据
				if (this.secondCategoryData[secondIndex]) {
					this.thirdCategoryData = this.secondCategoryData[secondIndex].child || []
				}
			}
			
			// 设置选中的分类
			const first = this.categoryData[firstIndex]
			const second = this.secondCategoryData[secondIndex]
			const third = this.thirdCategoryData[thirdIndex]
			
			if (first && second) {
				if (third) {
					this.formData.shopType = `${first.name}-${second.name}-${third.name}`
					this.shopClassData = [
						{ id: first.id, value: first.name },
						{ id: second.id, value: second.name },
						{ id: third.id, value: third.name }
					]
				} else {
					this.formData.shopType = `${first.name}-${second.name}`
					this.shopClassData = [
						{ id: first.id, value: first.name },
						{ id: second.id, value: second.name }
					]
				}
			}
		},
		
		// 表单验证
		validateForm() {
			const { shopName, licenseName, creditId, managerName, managerTel, areaName, shopType, shopDetailAddress } = this.formData
			
			if (!shopName) {
				uni.showToast({ title: '请填写店铺名称', icon: 'none' })
				return false
			}
			
			if (!licenseName) {
				uni.showToast({ title: '请填写店铺营业执照名称', icon: 'none' })
				return false
			}
			
			if (!creditId) {
				uni.showToast({ title: '请填写社会统一信用码', icon: 'none' })
				return false
			}
			
			// 验证统一社会信用代码格式
			const creditIdReg = /^(\d{15})|([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10})$/
			if (!creditIdReg.test(creditId)) {
				uni.showToast({ title: '社会统一信用码格式有误', icon: 'none' })
				return false
			}
			
			if (!managerName) {
				uni.showToast({ title: '请填写负责人姓名', icon: 'none' })
				return false
			}
			
			if (!managerTel) {
				uni.showToast({ title: '请填写负责人手机号码', icon: 'none' })
				return false
			}
			
			// 验证手机号格式
			const phoneReg = /^1[3-9]\d{9}$/
			if (!phoneReg.test(managerTel)) {
				uni.showToast({ title: '手机号码格式错误', icon: 'none' })
				return false
			}
			
			if (!areaName) {
				uni.showToast({ title: '请选择店铺所在省市', icon: 'none' })
				return false
			}
			
			if (!shopType) {
				uni.showToast({ title: '请选择店铺类型', icon: 'none' })
				return false
			}
			
			if (this.shopClassData.length < 2) {
				uni.showToast({ title: '请选择有 "三级分类" 的店铺类型', icon: 'none' })
				return false
			}
			
			if (!shopDetailAddress) {
				uni.showToast({ title: '请填写店铺详细地址', icon: 'none' })
				return false
			}
			
			return true
		},
		
		// 下一步
		nextStep() {
			if (!this.validateForm()) {
				return
			}
			
			// 保存数据到本地存储
			const businessInfo = uni.getStorageSync('businessInfo') || {}
			businessInfo.page2 = {
				shop_name: this.formData.shopName,
				license_name: this.formData.licenseName,
				uscc: this.formData.creditId,
				manager_name: this.formData.managerName,
				manager_tel: this.formData.managerTel,
				first_cate_id: this.shopClassData[0]?.id || '',
				second_cate_id: this.shopClassData[1]?.id || '',
				third_cate_id: this.shopClassData[2]?.id || '',
				shop_province_id: this.addrIdArr[0]?.id || '',
				shop_city_id: this.addrIdArr[1]?.id || '',
				shop_district_id: this.addrIdArr[2]?.id || '',
				area_name: this.formData.areaName,
				shop_detail_address: this.formData.shopDetailAddress,
				addriddata: this.addrIdArr,
				shopClass: this.shopClassData
			}
			
			uni.setStorageSync('businessInfo', businessInfo)
			
			// 跳转到下一页
			const pages = getCurrentPages()
			const currentPage = pages[pages.length - 1]
			const options = currentPage.options
			
			if (options.id) {
				uni.navigateTo({
					url: `/pages/identity/upload_bussinessPhoto?id=${options.id}`
				})
			} else {
				uni.navigateTo({
					url: '/pages/identity/upload_bussinessPhoto'
				})
			}
		}
	}
}
</script>

<style scoped>
.page {
	background: #eeeeee;
	min-height: 100vh;
}

.header-bag {
	display: flex;
	align-items: center;
	height: 88rpx;
	background: #fff;
	position: relative;
}

.back {
	width: 40rpx;
	height: 40rpx;
	margin-left: 30rpx;
}

.header-center {
	position: absolute;
	left: 50%;
	transform: translateX(-50%);
	font-size: 36rpx;
	font-weight: bold;
}

.wrapper {
	padding: 40rpx 0;
	font-size: 28rpx;
}

.info-box {
	background: white;
	/* margin-top: 40rpx; */
	padding: 0 30rpx;
	border-bottom: 2rpx solid #e8e8e8;
}

.layouts {
	display: flex;
	height: 90rpx;
	align-items: center;
	border-bottom: 2rpx solid #e8e8e8;
}

.layouts:last-child {
	border-bottom: none;
}

.label {
	width: 41%;
	display: flex;
	align-items: center;
}

.must-write {
	color: red;
	margin-right: 10rpx;
}

.input-wrapper {
	position: relative;
	width: 59%;
}

.input-wrapper input {
	height: 100rpx;
	width: 85%;
	color: #4b4b4b;
	font-size: 28rpx;
}

.del-text {
	position: absolute;
	right: 0;
	top: 50%;
	transform: translateY(-50%);
	width: 40rpx;
	height: 40rpx;
}

.notice-text {
	padding: 100rpx 60rpx;
	color: red;
	font-size: 24rpx;
}

.next-step {
	width: 690rpx;
	height: 90rpx;
	line-height: 90rpx;
	color: white;
	background: #ff2e00;
	border-radius: 10rpx;
	text-align: center;
	margin: 0 auto;
	margin-top: 40rpx;
}

.picker-container {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: white;
	z-index: 1001;
}

.picker-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 80rpx;
	padding: 0 30rpx;
	border-bottom: 2rpx solid #DCDCDC;
	font-size: 28rpx;
}

.picker-cancel {
	color: #666;
}

.picker-title {
	font-size: 30rpx;
	font-weight: bold;
}

.picker-confirm {
	color: #1e83d3;
}

.picker-view {
	height: 500rpx;
}

.mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
}
</style>